<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="about">
      <!-- 筛选区域 -->
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <div>选择用户:</div>
        <a-select v-model:value="selectedUserId" placeholder="选择用户" style="width: 200px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="user in userOptions" :key="user.value" :value="user.value">
            {{ user.label }}
          </a-select-option>
        </a-select>

        <a-button type="primary" @click="handleFilter">检索</a-button>
        <a-button @click="resetFilter">重置</a-button>
        <a-button type="primary" @click="showModal">新增</a-button>
      </a-space>

      <!-- 表格 -->
      <a-table
          :columns="columns"
          :row-key="item => item.searchId"
          :data-source="searchHistories"
          :pagination="pagination"
          :loading="isLoading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'keyWord'">
            <span>{{ record.keyWords }}</span>
          </template>
          <template v-if="column.dataIndex === 'searchTime'">
            <span>{{ formatDate(record.searchTime) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">编辑</a-button>
              <a-popconfirm title="是否确认要删除?" ok-text="Yes" cancel-text="No" @confirm="deleteSearch(record)">
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>

  <!-- 编辑或新增模态框 -->
  <a-modal v-model:open="open" title="编辑搜索记录" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form :model="selectedRecord" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="用户">
        <a-select v-model:value="selectedRecord.userId" :options="userOptions" />
      </a-form-item>
      <a-form-item label="关键词">
        <a-input v-model:value="selectedRecord.keyWords" />
      </a-form-item>
      <a-form-item label="搜索时间">
        <a-date-picker v-model:value="selectedRecord.searchTime" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
/* eslint-disable */
interface SearchHistory {
  searchId: number;
  userId: number | undefined;
  keyWords: string;
  searchTime: string;
}

const searchHistories = ref<SearchHistory[]>([]);
const selectedUserId = ref<number | ''>('');
const userOptions = ref<{ value: number; label: string }[]>([]);
const pagination = ref({
  pageSize: 10,
  total: 0,
  current: 1
});
const isLoading = ref(true);
const isSearch = ref(false);

// 分页信息
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchSearchHistories();
  } else {
    handleFilter();
  }
};

// 获取搜索历史列表
const fetchSearchHistories = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/searchHistory/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    searchHistories.value = res.data.data.list;
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

// 条件查询
const handleFilter = async () => {
  isLoading.value = true;
  isSearch.value = true;
  try {
    const res = await axios.post('/searchHistory/query', {
      userId: selectedUserId.value || undefined
    });
    isLoading.value = false;
    searchHistories.value = res.data.data;
    pagination.value.total = res.data.data.length;
  } catch (err) {
    console.error('筛选失败:', err);
    isLoading.value = false;
  }
};

// 重置筛选条件
const resetFilter = async () => {
  selectedUserId.value = '';
  isSearch.value = false;
  await fetchSearchHistories();
};

// 获取用户选项
const fetchUserOptions = async () => {
  try {
    const res = await axios.get('/users/list', {
      params: { page: 1, size: 100 }
    });
    userOptions.value = res.data.data.list.map((user: any) => ({
      value: user.userId,
      label: user.username
    }));
  } catch (err) {
    console.error('获取用户列表失败:', err);
    message.error('获取用户列表失败');
  }
};

// 显示编辑弹窗
const open = ref(false);
const confirmLoading = ref(false);
const selectedRecord = ref<SearchHistory>({
  searchId: 0,
  userId: undefined,
  keyWords: '',
  searchTime: ''
});

const showModal = (record: SearchHistory) => {
  open.value = true;
  selectedRecord.value = { ...record };
  // 将字符串日期转换为 dayjs 对象
  selectedRecord.value.searchTime = dayjs(record.searchTime);
};

// 提交编辑或新增
const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);
  axios.post('/searchHistory/update', {
    searchId: selectedRecord.value.searchId,
    userId: selectedRecord.value.userId,
    keyWords: selectedRecord.value.keyWords,
    searchTime: dayjs(selectedRecord.value.searchTime).format('YYYY-MM-DD HH:mm:ss')
  }).then(res => {
    if (res.data.code === 200) {
      message.success(res.data.message);
      if (!isSearch.value) {
        fetchSearchHistories();
      } else {
        handleFilter();
      }
    } else {
      message.error(res.data.message);
    }
  }).catch(() => {
    message.error('更新失败，请稍后重试');
  });
};

// 删除
const deleteSearch = (record: SearchHistory) => {
  axios.post('/searchHistory/delete', {
    searchId: record.searchId
  }).then(() => {
    message.success('删除成功');
    if (!isSearch.value) {
      fetchSearchHistories();
    } else {
      handleFilter();
    }
  }).catch(() => {
    message.error('删除失败');
  });
};




const showModal1 = () => {
  open1.value = true;
};


// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

onMounted(async () => {
  await fetchUserOptions();
  await fetchSearchHistories();
});

// 列定义
const columns = [
  { title: '用户', dataIndex: 'userId', customRender: ({ text }: { text: number }) => userOptions.value.find(u => u.value === text)?.label || '未知用户' },
  { title: '关键词', dataIndex: 'keyWords', customRender: ({ text }: { text: string }) => text },
  { title: '搜索时间', dataIndex: 'searchTime', customRender: ({ text }: { text: string }) => formatDate(text) },
  { title: '操作', dataIndex: 'action' }
];
</script>
